/**
 * 租户首页
 */
define(function (require, exports, module) {
    var $ = require("jquery");
    var util = require("util");
    var ui = require("ui");
    var _ = require('underscore');
    var storage = require("storage");
    var angular = require("angular");
    var authorize = require('authorize');
    require('angular-interceptor');
    require('permission');
    require('authorize');
    require("plugins/jquery.jcarousel");
    require('global');
    var popAd = require('/static_public/js/pop1Ad1');

    var environment = require("environment");
    var app = angular.module('app', ['ngInterceptor']);
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀

    // 查询服务
    function filterService($q, $http) {
        var service = {
            data: [],
            doQuery: function (pageIndex) {
                $q.all([service.getAllOfficialAccounts(), service.getUnauthWxUsers()])
                    .then(function (datas) {
                        var accounts = datas[0];
                        var unAuthUsers = datas[1];
                        var unAuthNames = _.map(unAuthUsers, function (user) {
                            return user.wxname;
                        });

                        var soonExpireds = [];
                        var expireds = [];
                        var fails = [];

                        // 显示公众号授权提示条件
                        function isShowUnAuthTip() {
                            var preUnAuthUsers = JSON.parse(localStorage.getItem('preUnAuthUsers'));
                            if ((unAuthNames.length > 0 && !preUnAuthUsers) || (preUnAuthUsers && _.difference(unAuthNames, preUnAuthUsers.list).length > 0)) {
                                localStorage.setItem('preUnAuthUsers', JSON.stringify({
                                    name: authorize.getUserInfo().userName,
                                    list: unAuthNames
                                }));
                                return true;
                            }
                        }

                        // 显示（即将失效、失效、认证失败）信息条件
                        function isShowExpiredTip() {
                            var mixedArr = _.union(soonExpireds, expireds, fails);
                            var preExpired = JSON.parse(localStorage.getItem('preExpired'));
                            if ((mixedArr.length > 0 && !preExpired) || (preExpired && _.difference(mixedArr, preExpired.list).length > 0)) {
                                localStorage.setItem('preExpired', JSON.stringify({
                                    name: authorize.getUserInfo().userName,
                                    list: mixedArr
                                }));
                                return true;
                            }
                        }

                        // 显示需要公众号授权提示
                        function showUnAuthTip() {
                            var userNames = _.uniq(_.map(unAuthUsers, function (user) {
                                return user.wxname;
                            }));
                            var userNamesSpan = '<span style="color: #3399FF">' + userNames.join(',') + '</span>';
                            var msgP = '<div class="gzh-error-icon"><p>当前公众号' + userNamesSpan + '已解除对明源云客平台授权，将导致云客应用无法正常使用，影响业务管理。</p>' +
                                '<p>您需重新将公众号权限集授权给云客，才能正常使用云客。</p>' +
                                '</div>';
                            var title = '信息提示';
                            if (unAuthUsers.length === 1) {
                                util.confirm(msgP, {
                                    title: title, width: 500,
                                    okValue: '马上授权',
                                    cancelValue: '以后再说',
                                    ok: function () {
                                        location.href = '/page/public_no/index.shtml?type=update&token=' + unAuthUsers[0].token;
                                    }
                                });
                            } else if (unAuthUsers.length > 1) {
                                util.alert(msgP, {title: title, width: 500, okValue: '我知道了'});
                            }
                        }

                        // 显示（即将失效、失效、认证失败）信息
                        function showExpiredTip() {
                            var title = '公众号资质认证提示';
                            var msgs = [];
                            soonExpireds.length > 0 && msgs.push('<p>公众号<span style="color: #3399FF">' + _.uniq(soonExpireds).join('、') + '</span>资质认证即将过期，请尽快完成年审认证，否则将影响高级接口及相关云客功能使用。</p>');
                            expireds.length > 0 && msgs.push('<p>公众号<span style="color: #3399FF">' + _.uniq(expireds).join('、') + '</span>资质认证已过期失效，无法使用高级接口及相关云客功能。请尽快重新认证。</p>');
                            fails.length > 0 && msgs.push('<p>公众号<span style="color: #3399FF">' + _.uniq(fails).join('、') + '</span>资质认证失败，无法使用高级接口及相关云客功能。请尽快重新认证。</p>');
                            msgs.length > 0 && util.alert('<div class="gzh-error-icon">' + msgs.join('<br>') + '</div>', {
                                title: title,
                                width: 500,
                                okValue: '我知道了'
                            });
                        }

                        _.each(accounts, function (company) {
                            _.each(company.data || [], function (weixin) {

                                // 当expiredTime=0时表示该公众号没有更新过认证状态，请不要处理
                                // expiredStatus 1即将失效，2失效且未认证失败，3是失效且认证失败，0未失效
                                if (parseInt(weixin.expiredTime) !== 0) {
                                    switch (weixin.expiredStatus) {
                                        case 1 :
                                            soonExpireds.push(weixin.weixinName);
                                            weixin.soonExpired = true;
                                            break;
                                        case 2 :
                                            expireds.push(weixin.weixinName);
                                            weixin.expired = true;
                                            break;
                                        case 3 :
                                            fails.push(weixin.weixinName);
                                            weixin.fail = true;
                                            break;
                                    }
                                }
                                if (_.contains(unAuthNames, weixin.weixinName)) {
                                    // 添加'公众号已取消对云客的授权'标志
                                    weixin.unbind = true;
                                }
                            });
                        });

                        var isShowUnAuthTipBol = isShowUnAuthTip();

                        isShowUnAuthTipBol && showUnAuthTip();

                        // 优先弹公众号授权提示
                        if (!isShowUnAuthTipBol && isShowExpiredTip()) {
                            showExpiredTip();
                        }
                    });
            },
            getAllOfficialAccounts: function () {
                var _this = this;
                var url = api_prefix + 'project/auth/get-all-official-accounts';
                return $http.get(url)
                    .then(function (res) {
                        var accounts = service.data = res.data.data || [];
                        setTimeout(function () {
                            _this.bindEvent();
                        }, 1000);
                        return accounts;
                    });
            },
            //获取当前租户取消了授权的第三方授权公众号
            getUnauthWxUsers: function () {
                var url = api_prefix + 'authorization/weixin-user/get-unauth-wx-users';
                return $http.get(url).then(function (res) {
                    var users = res.data.data || [];
                    return users;
                });
            },
            // 删除
            delete: function (data) {
                if (data.list && data.list.length > 0) {
                    util.alert("该公众号已经绑定项目应用，不允许删除");
                } else {
                    util.confirm("您确定要删除该公众号的信息吗？", {
                        ok: function () {
                            var url = api_prefix + 'authorization/weixin-user/del-account';
                            $http.post(url, {token: data.token})
                                .success(function (data) {
                                    ui.showSucTip('删除成功');
                                    service.doQuery();
                                })
                        }
                    });
                }
            },
            // 应用列表滚动
            scroll: function (arr) {
                var len = arr.length;
                if (len < 1) {
                    return
                }
                for (var i = 0; i < len; i++) {
                    $('#scroll' + arr[i]).jcarousel({
                        wrap: "last"
                    });
                    $('.prev_' + arr[i])
                        .on('jcarouselcontrol:active', function () {
                            $(this).removeClass('inactive');
                        })
                        .on('jcarouselcontrol:inactive', function () {
                            $(this).addClass('inactive');
                        })
                        .jcarouselControl({
                            target: '-=1'
                        });
                    $('.next_' + arr[i])
                        .on('jcarouselcontrol:active', function () {
                            $(this).removeClass('inactive');
                        })
                        .on('jcarouselcontrol:inactive', function () {
                            $(this).addClass('inactive');
                        })
                        .jcarouselControl({
                            target: '+=1'
                        });
                }
            },
            // 收集需要滚动的列表 (当应用数大于7时)
            getScrollId: function () {
                var data = this.data,
                    len = data.length,
                    arr = [];
                for (var i = 0; i < len; i++) {
                    var item = data[i].data;
                    for (var j = 0; j < item.length; j++) {
                        if (item[j].list.length > 7) {
                            arr.push(item[j].token)
                        }
                    }
                }
                return arr;
            },
            bindEvent: function () {
                this.scrollAd();
                this.scroll(this.getScrollId());
                // 绑定tab切换
                $(".gzh-item-btn").on("click", function () {
                    var _this = $(this);
                    var brotherNum, $brother;
                    var rel = _this.attr("data-rel");
                    var num = _this.attr("data-num");
                    if (num === "1") {
                        brotherNum = "2";
                        $brother = _this.next();
                    } else {
                        brotherNum = "1";
                        $brother = _this.prev();
                    }
                    _this.addClass("current");
                    $brother.removeClass("current");
                    $("#" + rel + num).show();
                    $("#" + rel + brotherNum).hide();
                });
            },
            // 滚动头部的广告
            scrollAd: function () {
                $('#adSlideBox').jcarousel({
                    wrap: "both"
                }).jcarouselAutoscroll({
                    interval: 4000,
                    target: '+=1',
                    autostart: true
                });
                $('#adPrev').jcarouselControl({
                    target: '-=1'
                });
                $('#adNext').jcarouselControl({
                    target: '+=1'
                });
                $('#adSlideBtn')
                    .on('jcarouselpagination:active', 'a', function () {
                        $(this).addClass('tb-slide-on');
                    })
                    .on('jcarouselpagination:inactive', 'a', function () {
                        $(this).removeClass('tb-slide-on');
                    })
                    .jcarouselPagination();
            }
        }
        return service;
    }

    app.factory('filters', ['$q', '$http', filterService]);

    function queryService($scope, filters) {
        filters.doQuery();
        $scope.query = filters;
        $scope.delete = function (id) {
            filters.delete(id);
        };
        $scope.oneBtnAuth = function (token) {
            var msgP = '<div class="gzh-error-icon">' +
                '<p>当前公众号是以开发者模式手工绑定云客应用。</p>' +
                '<br>' +
                '<p>建议采用新的“一键授权”方式绑定云客，以便使用我们提供的更稳定、丰富的微信接入服务，包括新的微信管理模块和第三方微信应用（游戏、互动营销等）接入。</p>' +
                '<br>' +
                '<p style="color: #ff7713">公众号一键授权给云客之后，如您此前曾通过手工方式，在第三方应用平台做了公众号绑定配置，这些配置都将失效。第三方应用必须按照云客开放API进行对接开发之后，方能正常使用。</p>' +
                '</div>';
            var title = '公众号一键授权提示';
            util.confirm(msgP, {
                title: title, width: 500,
                okValue: '马上补一键授权',
                cancelValue: '以后再说',
                ok: function () {
                    location.href = '/page/public_no/index.shtml?type=update&token=' + token;
                }
            });
        };
        $scope.links = {
            "5001": "/api/index.php?r=site/redirect-to&page=wls1&",   // 微楼书(旧版)
            "5002": "/page/customer_distribution/index.html?",  // 移动销售
            "5003": "/page/home/home.shtml?",                         // 全民营销
            "5004": "/page/app_store/index.shtml?",                   // 互动传播
            "5008": "/page/intermediary_organ/bee/index.shtml?",       // 小蜜蜂
            "5009": environment.wls + "/wls/index.html?",                    // 微楼书(新版)
            "5020": environment.ztcsh + "/index.php?r=yunke/index&",           // 秒杀活动
            "5021": "/page/raise_finance/activities.shtml?",          // 认筹理财
            "5022": environment.mysrc + "/ydxs_static/page/proxy.ashx?code=cst_assign&",   // 移动销售简版(移动跟客)
            "5030": "/page/wangcaibao/call_manage.shtml?"   // 旺财宝
        }
    }

    app.controller('queryService', ['$scope', 'filters', queryService]);

    setTimeout(function () {
        var adImg = 'http://img-dev.myscrmimg.cn/static_public/ad/2016_01/new_year_day_index.jpg';
        var animImg = 'http://img-dev.myscrmimg.cn/static_public/ad/2016_01/new_year_day_5-6.png';

        popAd.run({
            key: 'new_year_day_index',
            html: '<div style="width:550px;height:650px;">' +
            '<div style="position:relative;opacity: 0;" id="js_new_year_day_index_wrapper">' +
            '<img src="' + adImg + '" usemap="#Map">' +
            '<map name="Map" id="Map">' +
            '<area shape="rect" coords="490,2,550,50" class="js_close_btn" href="javascript:;"/>' +
            '</map>' +
            '<div style="position:absolute;top:386px;left:233px;width:52px;height:84px;overflow:hidden;">' +
            '<img id="js_new_year_day_index_img" style="position:absolute;width:100%;top:3px;" src="' + animImg + '">' +
            '</div>' +
            '</div>' +
            '</div>',
            expires: 7,
            startTime: new Date(2016, 0, 1, 0, 0, 0, 0).getTime(),
            endTime: new Date(2016, 0, 4, 0, 0, 0, 0).getTime(),
            timeout: 10000,
            preLoadImages: [adImg, animImg],
            show: function (pop) {
                $('#js_new_year_day_index_wrapper')
                    .css({
                        marginTop: 100
                    })
                    .animate({opacity: 1, marginTop: 0}, 1000, function () {
                        setTimeout(function () {
                            $('#js_new_year_day_index_img').animate({
                                top: -76
                            }, 500);
                        }, 300);
                    });
            }
        });
    }, 4000);

    angular.bootstrap(document, ['app']);
});